package com.fintech.pangu.upms.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fintech.pangu.upms.web.dao.SysRolePermissionDao;
import com.fintech.pangu.upms.web.dto.SysRolePermissionDto;
import com.fintech.pangu.upms.web.entity.SysRolePermission;
import com.fintech.pangu.upms.web.service.SysRolePermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Admin
 * @since 2019-10-08
 */
@Service
public class SysRolePermissionServiceImpl implements SysRolePermissionService {

    @Autowired
    private SysRolePermissionDao sysRolePermissionDao;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addRolePermission(SysRolePermissionDto sysRolePermissionDto) {
        // 先删后增
        QueryWrapper<SysRolePermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysRolePermission::getRoleId,sysRolePermissionDto.getRoleId());
        sysRolePermissionDao.delete(queryWrapper);

        Optional.ofNullable(sysRolePermissionDto.getPermissionIds())
                .ifPresent(list -> list.stream()
                        .forEach(permissionId ->{
                            SysRolePermission sysRolePermission = new SysRolePermission();
                            sysRolePermission.setRoleId(sysRolePermissionDto.getRoleId());
                            sysRolePermission.setPermissionId(permissionId);
                            sysRolePermissionDao.insert(sysRolePermission);
                                }
                        )
                );
    }
}
